<?php 

/*
 * This file will perform the searching of documents for the user.
 * 
 * Created by: Peter Agno Jr.
 * Date created: September 17, 2011
 */

    include("siteTop.php"); 
    
    include('includes/siteConfig.php'); 

    // connect to database
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
    
    // Get the document event that will be searched
    $documentEvent = $_GET['documentEvent'];
?>

<!-- HEADER START -->
    <!--JAVASCRIPT SOURCES-->
    <script src="js/jquery-1.6.2.min.js"></script>
    
    <!--ACTUAL JS SCRIPTS AND JQUERIES-->
    <script type="text/javascript">
        // VARIABLES FOR SEARCH RESULTS AND PAGINATION
        var varRow, pageNum, viewRowLimit, rowCount, hideRow, viewPageNumLimit, viewCount, firstRow;
        
        jQuery(document).ready(function(){
            // CHANGE FIRST THE CSS OF THE NAV BAR
            jQuery("#search-nav").addClass("highlightMenuBar");
            
            // Change the document event drop down
            jQuery("#documentEvent").val("All"); // Initially All
            jQuery("#documentEvent").val("<?php echo $documentEvent; ?>");
            
            jQuery("#documentName").focus();
            
            // START - Ajax for search when enter button was clicked.
            jQuery(".inputbox").keypress(function(e){
               if(e.keyCode == 13) {
                    jQuery("#searchButton").click();
               }
            }); // END - Ajax for search when enter button was clicked.
            
            searchDocs(); // Update the searchedDocument table
            
            // START - JQUERY FOR SEARCH
            jQuery('#searchButton').live("click",function() {
                searchDocs();
            }); // END - JQUERY FOR SEARCH
                
            // START - JQUERY FOR TRANSFERRING TO VIEW PAGE OF THE DOCUMENT
            jQuery('.hLinkViewPage').live("click",function() {
               buttonId = this.id;

               // SET THE FORM THAT IT WILL BE SUBMITTED TO
               tempSubstr = buttonId.split('__');
               if ( tempSubstr[1] == "MainDocument" )
                    jQuery("#viewPageForm").attr("action", "viewPageSending.php");
                else
                    jQuery("#viewPageForm").attr("action", "viewPageAttachment.php");

                // SET THE DOCUMENT ID
                jQuery("#documentIdViewPage").val(tempSubstr[0]);

                // SUBMIT THE FORM
                jQuery("#viewPageForm").submit();
            }); // END - JQUERY FOR TRANSFERRING TO VIEW PAGE OF THE DOCUMENT
                    
            // START - JQUERY FOR PAGINATION
            jQuery('.pageButton').live("click",function() {
                buttonId = this.id;

                tempSubstr = buttonId.split('_');
                totalPageNum = jQuery("#totalPageNum").val();
                viewPageNumLimit = jQuery("#viewPageNumLimit").val();

                // HIDE ALL ROWS IN THE SEARCH RESULTS ASCENDING
                for ( i = 1 ; i < tempSubstr[1] ; i++ ) {
                    jQuery(".rowPage_"+i).hide();
                }

                // HIDE ALL ROWS IN THE SEARCH RESULTS DESCENDING
                for ( i = totalPageNum ; i > tempSubstr[1] ; i-- ) {
                    jQuery(".rowPage_"+i).hide();
                }

                // SHOW THE SELECTED ROWS
                jQuery("."+buttonId).show();

                // SHOW ONLY LIMITED NUMBERS OF PAGE, DEPENDING ON THE viewPageNumLimit
                if ( totalPageNum > viewPageNumLimit ) {
                    // DECREMENT AND SET THE prevPageButton
                    prevPage = parseInt(parseFloat(tempSubstr[1])) - 1;
                    jQuery(".prevPageButton").attr("id", "rowPage_"+prevPage);

                    // INCREMENT AND SET THE nextPageButton
                    nextPage = parseInt(parseFloat(tempSubstr[1])) + 1;
                    jQuery(".nextPageButton").attr("id", "rowPage_"+nextPage);

                    // HIDE ALL PAGINATION BUTTONS
                    jQuery(".pageButton").hide();

                    // SHOW PAGINATION NUMBERS WITHIN viewPageNumLimit
                    for ( i = parseInt( tempSubstr[1] ) - ( parseInt( viewPageNumLimit / 2 ) ), viewCount = 1 ; i <= totalPageNum && viewCount <= viewPageNumLimit ; i++, viewCount++ ) {
                        jQuery(".buttonNum_"+i).show();
                    }

                    // SHOW SPECIAL PAGINATION BUTTONS
                    jQuery(".firstPageButton").show();
                    jQuery(".prevPageButton").show();
                    jQuery(".nextPageButton").show();
                    jQuery(".lastPageButton").show();

                    // HIDE nextPageButton AND lastPageButton IF THE LAST PAGE OR FINAL NUMBER WAS CLICKED
                    if ( tempSubstr[1] == totalPageNum ) {
                        jQuery(".nextPageButton").hide();
                        jQuery(".lastPageButton").hide();
                    }

                    // HIDE firstPageButton AND prevPageButton IF THE FIRST PAGE OR PAGE 1 WAS CLICKED
                    if ( tempSubstr[1] == 1 ) {           
                        jQuery(".prevPageButton").hide();
                        jQuery(".firstPageButton").hide();
                    }


                }

                // UPDATE THE PREVIOUS PAGE BUTTON
                // jQuery(".pageButton").css({ 'color': 'blue' });
                jQuery(".pageButton").removeClass("paginationCurrentPage").addClass("paginationPageNumbers");

                // COLOR THE CLICKED PAGINATION NUMBER
                // jQuery(".buttonNum_"+tempSubstr[1]).css({ 'color': 'red' });
                jQuery(".buttonNum_"+tempSubstr[1]).removeClass("paginationPageNumbers").addClass("paginationCurrentPage");
            }); // END - JQUERY FOR PAGINATION   
            
            // Start - Ajax for searching the documents
            function searchDocs() {
                // START - AJAX FOR SEARCH
                jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/searchDocuments.php',
                    dataType : 'json',
                    data: {
                        documentType : jQuery("#documentType").val(),
                        documentName : jQuery("#documentName").val(),
                        documentId : jQuery("#documentId").val(),
                        label : jQuery("#label").val(),
                        documentEvent : jQuery("#documentEvent").val()
                    },
                    success : function(data){
                        // REMOVE THE LISTED DOCUMENTS IN THE TABLE
                        jQuery("#searchedDocument").children().remove();
                            
                        // If, there are querried documents
                        if (data) {
                            // IF RETURNED QUERY IS EMPTY, THEN MESSAGE THE USER THAT THE RETURNED QUERY IS EMPTY
                            if ( data == null ) {
                                varRow = "<tr><td colspan='4'><span class='errorMessage'>No documents found.</span></td></tr>";
                                jQuery(".searchedDocumentList").append(varRow);
                            }
                            else {
                                // APPEND THE HEADER
                                jQuery(".searchedDocumentList").append("<tr><th>Document Id</th><th>Document Name</th><th>Document Type</th><th style='display:none;'>Document Event</th></tr>");

                                // INCLUDE - SET THE VARIABLES FOR THE PAGINATION
                                <?php include("includes/jqueries/jQSetPaginationVar.php"); ?>

                                // START - APPEND SEARCHED DOCUMENTS
                                jQuery.each(data, function(index, data) {

                                    // INCLUDE - SET THE VISIBILITY OF THE ROW FOR PAGINATION
                                    <?php include("includes/jqueries/jQVisibilityRowPagination.php"); ?>

                                    varRow += "<td><a href='javascript:;' class='hLinkViewPage' id='"+data.documentId+"__"+data.documentType+"'>";
                                    varRow += data.documentId+"</a></td>";
                                    varRow += "<td>"+data.documentName+"</td>";

                                    if ( data.documentType == 'MainDocument' ) 
                                        varRow += "<td>Main Document</td>";
                                    else
                                        varRow += "<td>"+data.documentType+"</td>";

                                    varRow += "<td style='display:none;'>"+data.activity+"</td>";
                                    varRow += "</tr>";

                                    jQuery(".searchedDocumentList").append(varRow);
                                }); // END - APPEND SEARCHED DOCUMENTS
                                
                                columnNum = "4"; // Set this for the colspan of the paginationNumBar
                                appendTo = "searchedDocumentList"; // Table on where it will be appended
                       
                                // START - CREATING THE PAGINATION NUMBER BAR
                                // IF THERE IS ONLY ONE PAGE, THEN DON'T SHOW PAGINATION
                                if ( pageNum != 1 ) {
                                    varRow = "<tr class='paginationNumBar'><td colspan='"+columnNum+"' align='center'><div class='paginationNumBarDiv'>";

                                    // IF THE ACCUMULATED (OR TOTAL) $pageNum > $viewPageNumLimit THEN SHOW ONLY $viewPageNumLimit OF PAGE NUMBERS, AND DON'T SHOW FIRST 
                                    if ( pageNum > viewPageNumLimit ) {
                                        varRow += "<input style='display:none;' class='paginationBtnCss paginationPageNumbers pageButton firstPageButton' id='rowPage_1' type='button' value='First' /> ";
                                        varRow += "<input style='display:none;' class='paginationBtnCss paginationPageNumbers pageButton prevPageButton' id='rowPage_1' type='button' value='Previous' /> ";

                                        for ( i = 1 ; i <= pageNum ; i++ ) {
                                            if ( i <= viewPageNumLimit ) {
                                                if ( firstRow == true ) {
                                                    firstRow = false;
                                                    varRow += "<input class='paginationCurrentPage ";
                                                }
                                                else {
                                                    varRow += "<input class='paginationPageNumbers ";
                                                }
                                            }
                                            else {
                                                varRow += "<input style='display:none;' class='paginationPageNumbers ";
                                            }

                                            varRow += "paginationBtnCss pageButton buttonNum_"+i+"' id='rowPage_"+i+"' type='button' value='"+i+"' /> ";
                                        }

                                        varRow += "<input class='paginationBtnCss paginationPageNumbers pageButton nextPageButton' id='rowPage_2' type='button' value='Next' /> ";
                                        varRow += "<input class='paginationBtnCss paginationPageNumbers pageButton lastPageButton' id='rowPage_"+pageNum+"' type='button' value='Last' /> ";
                                    }
                                    else {
                                    // ELSE, SHOW ALL PAGE NUMBERS
                                        for ( i = 1 ; i <= pageNum ; i++ ) {                    
                                            if ( firstRow == true ) {
                                                firstRow = false;
                                                varRow += "<input class='paginationCurrentPage ";
                                            }
                                            else {
                                                varRow += "<input class='paginationPageNumbers ";
                                            }

                                            varRow += "paginationBtnCss pageButton buttonNum_"+i+"' id='rowPage_"+i+"' type='button' value='"+i+"' /> ";
                                        }
                                    }

                                    varRow += "</div></td></tr>";
                                    jQuery("."+appendTo).append(varRow);
                                }

                                jQuery("#totalPageNum").val(pageNum);
                                // END - CREATING THE PAGINATION NUMBER BAR                                                                                    
                             
                            }
                        } // End if, there are querried documents
                        else {
                        // No data returned from ajax, so make it empty
                            varRow = "<tr><td colspan='4'><span class='errorMessage'>No documents found.</span></td></tr>";
                            jQuery(".searchedDocumentList").append(varRow);
                        }
                    },
                    error : function() {
                        alert("Error in searching the documents.");
                    }
                }); // END - AJAX FOR SEARCH
            } // End - Ajax for searching the documents
            
        });
    </script>
    <!-- HEAD END -->
    
<?php include("siteMiddle.php"); ?>
    
<div id="content">
    <h1>Search</h1>
    
    <?php
    // Check permission
    $thePermissions = array('VIEWMAIN', 'VIEWATTCH');
    if ( checkPermission( $thePermissions, $userId ) == true ) {
    ?>

    <!-- START - CREATE SEARCH FILTERS -->
    <span class="screenlet" >Search Filters</span>
    <table>
        <tr>
            <td>Document Type : </td>
            <td>
                <select name="documentType" id="documentType">
                    <option value="All">All</option>
                    <option value="MainDocument">Main Document</option>
                    <option value="Attachment">Attachment</option>
                </select>
            </td>
        </tr>

        <tr>
            <td>Document Name : </td>
            <td><input type="text" value="" name="documentName" id="documentName" class="inputbox" /></td>
        </tr>

        <tr>
            <td>Document Id : </td>
            <td><input type="text" value="" name="documentId" id="documentId" class="inputbox" /></td>
        </tr>

        <tr>
            <td>Label : </td>
            <td><input type="text" value="" name="label" id="label" class="inputbox" /></td>
        </tr>

        <tr>
            <td>Document Event : </td>
            <td>
                <select name="documentEvent" id="documentEvent">
                <?php

                // GET THE DOCUMENT EVENTS
//                $query =
//                    "
//                        SELECT activity
//                        FROM Log
//                        GROUP BY activity
//                        ORDER BY activity
//                    ";
//
//                $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
//
//                echo "<option value='All'>All</option>";
//                while( $row = mysql_fetch_array($result) ) {
//                    echo "<option value='".$row['activity']."'>".$row['activity']."</option>";
//                }
                
                    // Do the hardcode documentEvent
                    echo "<option value='All'>All</option>";
                    echo "<option value='Approved'>Approved</option>";
                    echo "<option value='Archived'>Archived</option>";
                    echo "<option value='Cancelled'>Cancelled</option>";
                    echo "<option value='Rejected'>Rejected</option>";
                    echo "<option value='Returned'>Returned</option>";
                    echo "<option value='Tagged'>Routed</option>";
                    echo "<option value='Sent'>Sent</option>";
                ?>
                </select>
            </td>
        </tr>

        <tr>
            <td></td>
            <td><input type="Submit" name="searchButton" id="searchButton" value="Search" class="siteGreenButton" /></td>
        </tr>
    </table>
    <!-- END - CREATE SEARCH FILTERS -->

    <!-- START - CREATE SEARCH RESULTS -->
    <span class="screenlet" >Search Results</span>
    <table border="1" name="searchedDocument" id="searchedDocument" class="searchedDocumentList">
        <?php
            // INCLUDE - SET THE VARIABLES FOR THE PAGINATION
            include('includes/variables/setPaginationVariables.php');
        ?>
    </table>
    <?php 
        // INCLUDE - HIDDEN VARIABLES USED FOR PAGINATION
        include('includes/variables/hiddenVarPagination.php'); 
    ?>

    <!-- END - CREATE SEARCH RESULTS -->
    <?php

    }
    else {
        echo "<div class='noPermissionMsgBox noPermissionMsg' style='border: 2px solid red'><div id='noPermissionMsgs'>You have no permission to view this page.</div></div>";
    }
    // End checking permission
    ?>
</div>
    
<!-- INVISIBLE FORM WHICH WILL BE USED FOR TRANSFERRING THE DOCUMENT TO ITS VIEW PAGE -->
<form id="viewPageForm" name="viewPageForm" action="" method="post">
    <input id="documentIdViewPage" name="documentId" type="hidden" value="" />
</form>

<?php     
    include ("siteBottom.php"); 
?>